package cn.flant.io.tcp;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;


public class StringMessageHandler extends MessageHandler {
	private boolean containsSeperator;
	private String startSeperator;
	private String endSeperator;
	private MessageReader reader;
	private BufferedWriter writer;

	public StringMessageHandler(boolean containsSeperator, String startSeperator, String endSeperator) {
		this.containsSeperator = containsSeperator;
		this.startSeperator = startSeperator;
		this.endSeperator = endSeperator;
	}

	public StringMessageHandler(String startSeperator, String endSeperator) {
		this(false, startSeperator, endSeperator);
	}

	public StringMessageHandler(String endSeperator) {
		this(false, null, endSeperator);
	}

	public StringMessageHandler() {
	}

	@Override
	public void onConnected(Socket socket) throws IOException {
		reader = new MessageReader(socket.getInputStream(), getCharset());
		reader.setContainsSeperator(containsSeperator);
		reader.setStartSeperator(startSeperator);
		reader.setEndSeperator(endSeperator);
		writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), getCharset()));
	}

	public boolean isContainsSeperator() {
		return containsSeperator;
	}

	public void setContainsSeperator(boolean containsSeperator) {
		this.containsSeperator = containsSeperator;
	}

	public String getStartSeperator() {
		return startSeperator;
	}

	public void setStartSeperator(String startSeperator) {
		this.startSeperator = startSeperator;
	}

	public String getEndSeperator() {
		return endSeperator;
	}

	public void setEndSeperator(String endSeperator) {
		this.endSeperator = endSeperator;
	}

	@Override
	public Object readMessage() throws IOException {
		return reader.readStringMessage();
	}

	@Override
	public void sendMessage(Object message) throws IOException {
		writer.write((String) message);
		writer.flush();
	}

	@Override
	public void onClosed() {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
			}
			reader = null;
		}
		if (writer != null) {
			try {
				writer.close();
			} catch (IOException e) {
			}
		}
	}

}
